#!/bin/sh

dir="${1}"
shift 1

if [ -z "${dir}" ]
then
    1>&2 echo "usage:"
    1>&2 echo "  ${0} <directory> [<option>]"
    exit 1
fi

set -x

nproc="${NPROC:-32}"


cat | grep '[.]epub$' | print0 | xargs -0 -I {} -n 1 -P "$nproc" sh -c 'set -e; [ -f "$2/$1.txt" ] && [ ! -s "$2/$1.txt" ] && echo "rm empty file: $2/$1.txt" && rm -f "$2/$1.txt" ; [ -f "$2/$1.txt" ] && echo "exists: $2/$1.txt" && exit 0 ; mkdir -p "${2}/$(dirname "$1")" ; echo "$1"; epubtxt "$1" | sponge "${2}/$1.txt"' -- "{}" "$dir"
